package com.xiaomaoguai.javassist.kepler.config;

import com.google.common.base.Joiner;
import com.xiaomaoguai.fcp.pre.kepler.convert.core.ConvertManager;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author huwenxuan
 * @date 2018/12/28
 */
@Getter
@AllArgsConstructor
public enum NodeSupport {

	/**
	 *
	 */
	IN("in"),

	/**
	 *
	 */
	OUT("out"),

	;

	private static Joiner DOT_JOINER = Joiner.on(".").skipNulls();

	private static final String DEFAULT = "default";

	/**
	 *
	 */
	private final String joiner;

	/**
	 * 现获取产品接口格转，拿不到就取默认格转
	 *
	 * 优先级：
	 * (1) 产品router格转
	 * (2) 默认router格转
	 *
	 * @param productCode 产品编码
	 * @param routerName  接口名
	 * @return router格转名称
	 */
	public String generateRouterConvertNodeName(String productCode, String routerName) {
		Assert.isTrue(StringUtils.isNoneBlank(productCode, routerName), "产品编码或者接口名称不能为空");
		//产品router格转
		String routerIn0 = DOT_JOINER.join(routerName, productCode, this.joiner);
		//默认router格转
		String routerIn1 = DOT_JOINER.join(routerName, DEFAULT, this.joiner);
		Optional<String> routerIn = Stream.of(routerIn0, routerIn1).filter(ConvertManager::contains).findFirst();
		return routerIn.orElse(null);
	}

	/**
	 * 现获取产品接口格转，拿不到就取默认格转
	 * 优先级：
	 * (1) handler对应router的格转
	 * (2) handler对应产品的格转
	 * (3) handler默认的格转
	 *
	 * @param productCode 产品编码
	 * @param routerName  接口名
	 * @return router格转名称
	 */
	public String generateHandlerConvertNodeName(String productCode, String routerName, String handlerName, String mockName) {
		Assert.isTrue(StringUtils.isNoneBlank(productCode), "产品编码或者接口名称不能为空");
		//router优先级
		String nodeName0 = getNodeName(routerName, handlerName, this.joiner, mockName);
		//productCode优先级
		String nodeName1 = getNodeName(productCode, handlerName, this.joiner, mockName);
		//handler优先级
		String nodeName2 = getNodeName(DEFAULT, handlerName, this.joiner, mockName);
		Optional<String> nodeName = Stream.of(nodeName0, nodeName1, nodeName2).filter(ConvertManager::contains).findFirst();
		return nodeName.orElse(null);
	}

	/**
	 * 根据midfix获取节点名称
	 *
	 * @param midfix
	 * @param name
	 * @param direct
	 * @param mockName
	 * @return
	 */
	private String getNodeName(String midfix, String name, String direct, String mockName) {
		List<String> collect = Arrays.stream(new String[]{name, midfix, direct, mockName}).filter(StringUtils::isNotBlank).collect(Collectors.toList());
		return DOT_JOINER.join(collect);
	}

}
